<template>
	<view class="container">
		<map 
			:latitude="latitude" 
			:longitude="longitude" 
			:markers="markers" 
			class="map"
			@markertap="handleMarkerTap">
		</map>
		<!-- 新增悬浮按钮 -->
		<view class="floating-btn" @click="gotoShopList">
			<text>附近门店</text>
		</view>
		
		<!-- 底部弹窗 -->
		<uni-popup ref="popup" type="bottom" background-color="#fff">
			<view class="popup-content">
				<view class="shop-info">
					<text class="title">{{ selectedShop?.title || '' }}</text>
					<text class="businessHours">{{ selectedShop?.businessHours || '' }}</text>
					<image :src="selectedShop?.storeImage" mode="aspectFill" style="width: 180rpx;height: 140rpx;position: relative;left: 90px;"></image>
					<text class="address">地址：{{ selectedShop?.address }}</text>
					<text class="distance">距离：{{selectedShop?._distance}}米</text>
				</view>
				
				<view class="button-group">
					<button class="btn contact" @tap="handleContact">联系门店</button>
					<button class="btn book" @tap="handleBooking">立即预定</button>
				</view>
				
				<view class="close-btn" @tap="closePopup">
					<uni-icons type="closeempty" size="24" color="#666"></uni-icons>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue'

let longitude = ref(); 
let latitude = ref();
let markers = ref([]);

const popup = ref(null);
const selectedShop = ref(null);

onMounted(() => {
  // 获取用户当前位置
  uni.getLocation({
    type: 'wgs84',
    success: (res) => {
      longitude.value = res.longitude;
      latitude.value = res.latitude;
      
      // 调用后端接口获取店铺数据
      fetchStoreData();
    },
    fail: (err) => uni.showToast({ title: '请授权位置信息', icon: 'none' })
  });
});

// 调用后端接口获取店铺数据
const fetchStoreData = () => {
   uni.request({
      url: 'http://localhost:9587/repairCar/AllStorelist',
      method: 'GET',
      success: (res) => {
        markers.value = res.data.rows.map((item, index) => {
          // 为每个店铺计算距离
          const _distance = calcDistance(
            latitude.value,
            longitude.value,
            item.latitude,
            item.longitude
          );
  
          return {
            id: item.storeId,
            title: item.storeName,
            latitude: item.latitude,
            longitude: item.longitude,
            address: item.address,
            businessHours: item.businessHours,
            storeImage: item.storeImage,
			storeId: item.storeId,
            tel: item.ext1,
            _distance: _distance, // 存储计算后的距离
            width: 30,
            height: 30
          };
        });
      },
      fail: (err) => console.error('获取失败:', err)
    });
};

// 处理标记点击
const handleMarkerTap = (e) => {
  const markerId = e.detail.markerId;
  selectedShop.value = markers.value.find(m => m.id === markerId);
  popup.value.open();
};

// 按钮事件处理
const handleContact = () => {
  if (!selectedShop.value?.tel) {
      uni.showToast({ title: '该店铺暂无联系方式', icon: 'none' });
      return;
    }
  
    // 新增确认弹窗
    uni.showModal({
      title: '联系门店',
      content: `是否拨打 ${selectedShop.value.tel}？`,
      success: (res) => {
        if (res.confirm) {
          // 处理特殊字符（如分机号）
          const cleanTel = selectedShop.value.tel.replace(/[^0-9+#*]/g, '');
          uni.makePhoneCall({ 
            phoneNumber: cleanTel,
            fail: (err) => {
              console.error('拨号失败:', err);
              uni.showToast({ title: '拨号失败，请检查号码', icon: 'none' });
            }
          });
        }
      }
    });
  }

// 计算两个经纬度点之间的距离（单位：米）
const calcDistance = (lat1, lng1, lat2, lng2) => {
  // 将角度转换为弧度
  const toRadians = (degree) => degree * Math.PI / 180;

  const R = 6371e3; // 地球半径（米）
  const φ1 = toRadians(lat1);
  const φ2 = toRadians(lat2);
  const Δφ = toRadians(lat2 - lat1);
  const Δλ = toRadians(lng2 - lng1);

  const a = Math.sin(Δφ / 2) * Math.sin(Δφ / 2) +
            Math.cos(φ1) * Math.cos(φ2) *
            Math.sin(Δλ / 2) * Math.sin(Δλ / 2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

  const distance = R * c;
  return Math.round(distance); // 四舍五入到整数
};

const handleBooking = () => {
	if (!selectedShop.value?.storeId) {
	    return uni.showToast({ title: '店铺信息异常', icon: 'none' })
	  }
	  
  uni.navigateTo({
    url: `/pages/booking/booking?storeId=${selectedShop.value.storeId}`
  });
};

const gotoShopList = () => {
  uni.navigateTo({
    url: `/pages/shopList/shopList?lat=${latitude.value}&lng=${longitude.value}`
  });
};

const closePopup = () => {
  popup.value.close();
};

</script>

<style>
.container{
	width: 100%;
	height: 100%;
}
		
.map{
	width: 100%;
	height: 100vh;
}

.popup-content {
  padding: 30rpx;
  position: relative;
}

.shop-info {
  margin-bottom: 40rpx;
}
.title {
  font-size: 36rpx;
  font-weight: bold;
  display: block;
  margin-bottom: 20rpx;
}
.address, .distance {
  font-size: 28rpx;
  color: #666;
  display: block;
  margin-bottom: 10rpx;
}

.button-group {
  display: flex;
  gap: 20rpx;
  padding-top: 20rpx;
  border-top: 1rpx solid #eee;
}

.btn {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  font-size: 30rpx;
  border-radius: 40rpx;
}
.contact {
  background-color: #f0f0f0;
  color: #333;
}
.book {
  background-color: #007AFF;
  color: white;
}

.close-btn {
  position: absolute;
  top: 20rpx;
  right: 20rpx;
  padding: 10rpx;
}

.floating-btn {
  position: fixed;
  right: 20px;
  bottom: 100px;
  background: #000;
  color: #fff;
  padding: 12px 24px;
  border-radius: 24px;
  z-index: 999;
  box-shadow: 0 2px 8px rgba(0,0,0,0.2);
}
</style>